package com.skz.web;

import cn.zhouyafeng.itchat4j.api.MessageTools;
import cn.zhouyafeng.itchat4j.api.WechatTools;
import com.skz.util.RedisKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: 宋开宗
 * @create: 2019-03-11 18:45
 **/
@RestController
@RequestMapping("/msg/groups")
public class MsgGroupSendController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 给每个群组发送消息
     *
     * @param text
     */
    @PostMapping
    public void sendMsg(String text) {
        stringRedisTemplate.opsForHash().values(RedisKey.GROUPS).forEach(o -> MessageTools.sendMsgById(text, o.toString()));
    }

    /**
     * 获取要发消息的群组
     *
     * @return
     */
    @GetMapping
    public ResponseEntity getSendGroups() {
        return ResponseEntity.ok(stringRedisTemplate.opsForHash().entries(RedisKey.GROUPS));
    }

    @PutMapping
    public ResponseEntity updateGroups() {
        Map<String, String> map = new HashMap<>(16);
        WechatTools.getGroupList().forEach(jsonObject -> {
            String groupName = jsonObject.getString("NickName");
            String groupId = jsonObject.getString("UserName");
            map.put(groupName, groupId);
        });
        stringRedisTemplate.opsForHash().keys(RedisKey.GROUPS).forEach(key -> {
            String id = map.get(key) == null ? "更新失败" : map.get(key);
            stringRedisTemplate.opsForHash().put(RedisKey.GROUPS, key, id);
        });
        return ResponseEntity.ok(stringRedisTemplate.opsForHash().entries(RedisKey.GROUPS));
    }
}
